import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    realName: '',
    role: '',
    roleLevel: null
  }
}
const state = getDefaultState();

const user = {
  namespaced: true,
  state: state,
  mutations: {
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_REALNAME: (state, realName) => {
      state.realName = realName
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    SET_ROLE_LEVEL: (state, roleLevel) => {
      state.roleLevel = roleLevel
    }
  },
  actions: {
    // 登录
    Login({commit}, loginForm) {
      return new Promise((resolve, reject) => {
        login(loginForm).then(resp => {
          setToken(resp.data.token);
          commit('SET_TOKEN', resp.data.token);
          resolve()
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 获取用户登录信息
    GetInfo({commit}) {
      return new Promise((resolve, reject) => {
        getInfo().then(resp => {
          const info = resp.data;
          commit('SET_USERNAME', info.username);
          commit('SET_REALNAME', info.realName);
          commit('SET_ROLE', info.roles[0].roleName);
          commit('SET_ROLE_LEVEL', info.roles[0].roleLevel);
          resolve(resp)
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 退出
    Logout({commit}) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          removeToken()
          resetRouter()
          commit('RESET_STATE')
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    ResetRouter() {
      return new Promise(resolve => {
        removeToken()
        commit('RESET_STATE')
        resolve()
      })
    }
  }
}

export default user
